package com.example.springbootrbac.handler;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.example.springbootrbac.pojo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static com.example.springbootrbac.pojo.ResultCode.FAILURE_LOGIN_OUT_TIME_ERROR;

@Component
public class SecurityLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private ObjectMapper objectMapper;

    //成功退出登录处理器
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        HttpSession session = request.getSession();
        if (ObjectUtils.isNotEmpty(session)){
            response
                    .getWriter()
                    .write(objectMapper.writeValueAsString(Result.success("退出成功")));
        }else {
            response
                    .getWriter()
                    .write(objectMapper.writeValueAsString(Result.failure(FAILURE_LOGIN_OUT_TIME_ERROR)));
        }
    }
}